<?php

namespace App\Controller\Center;

use App\Agent\PayAgent;
use App\Agent\StatisticsAgent;
use App\Agent\UserCacheAgent;
use App\Constants\ErrorCode;
use App\Constants\QmGame;
use App\Constants\RedisKey;
use App\Controller\InsideService\GameConfigInside;
use App\Controller\InsideService\GameUserInside;
use App\Controller\InsideService\PaySenderInside;
use App\Model\QmGameOrder;
use App\Model\QmGameVersion;
use App\Service\MiMasterService;
use App\Service\PayLogService;
use App\Service\QmGameService;
use App\Service\SlWechatService;
use App\Service\TiktokPayService;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

#[Controller(prefix: '/center/Pay')]
class PayController extends BaseController {
    /**
     * @Inject
     * @var ClientFactory
     */
    protected ClientFactory $clientFactory;

    #[GetMapping(path: 'index')]
    public function index(): array {
        $orderNum = $this->request->query('order_num', '');
        $orderInfo = QmGameOrder::query()->where('order_num', $orderNum)->first();
        if ($orderInfo) {
            return $this->buildSuccess($orderInfo->toArray());
        }

        return $this->buildFailed(ErrorCode::NOT_EXISTS, '订单不存在');
    }

    /**
     * 处理抖音服务器回调【TODO】
     * @return string|array
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     */
    #[RequestMapping(path: 'TtBack')]
    public function TtBack(): string|array {
        $requestData = $this->request->all();
        $needCheck = [
            $requestData['timestamp'],
            $requestData['nonce'],
            $requestData['msg'],
            'acJxCmKfErPmAAXupGMOlwtdodAifILo'
        ];
        sort($needCheck, SORT_STRING);
        $signature = sha1(implode('', array_values($needCheck)));
        if ($requestData['signature'] !== $signature) {
            return $this->buildFailed(ErrorCode::INVALID, '非法请求');
        }
        if ($this->request->isMethod('GET')) {
            return $this->request->query('echostr');
        }

        return $this->doBack($requestData['cp_orderno'], 1);
    }

    /**
     * 支付回调 按肆狼的支付回调改造
     * @return string
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping(path: 'back')]
    public function back(): string {
        $data = $this->request->post('data', '');
        $sign = $this->request->post('sign', '');
        $postData = json_decode($data, true);
        $channelId = $postData['channelid'];
        $productId = $postData['productid'];
        $amount = $postData['amount'];//单位是分
        $roleId = $postData['roleid'];
        $userId = $postData['userid'];
        $sub_userId = $postData['sub_userid'] ?? '123';
        $orderSn = $postData['order_sn'];
        $orderNum = $postData['app_order_id'];
        $serverId = $postData['serverid'];
        $payStatus = $postData['paystatus'];
        $orderext = $postData['orderext'] ?? '123';

        if (empty($channelId) || empty($productId) || empty($amount) || empty($roleId)
            || empty($userId) || empty($sub_userId) || empty($orderSn) || empty($orderNum)
            || empty($serverId) || empty($payStatus) || empty($orderext)) {
            return 'fail';//肆狼返回值如此
        }
        $res = (new SlWechatService())->payBackVerify($data, $sign);
        var_dump('微信支付回调验签结果');
        var_dump($res);
        if (!$res) {
            var_dump('微信支付回调验签失败');
            var_dump($data);
            var_dump($sign);
            return 'fail';
        }

        return $this->newDoBack($orderNum, $payStatus, $data);
    }

    /**
     * 肆狼版本响应支付回调
     * @param string $orderNum
     * @param int $status
     * @param array $postData
     * @return array
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     */
    private function newDoBack(string $orderNum, int $status, string $postData): string {
        $orderInfo = QmGameOrder::query()->where('order_num', $orderNum)->first();
        if ($orderInfo) {
            if ($orderInfo->status != 0) {
                return 'fail';
            }
            if ($status != 1 && $status != 2) {
                return 'fail';
            }
            if ($status == 1) {
                (new PaySenderInside())->sendReward($orderInfo->toArray());
            }

            $orderInfo->status = $status;
            $orderInfo->error_msg = $postData;
            $orderInfo->save();

            return 'success';
        }

        return 'fail';
    }


    /**
     * 响应支付回调
     * @param $orderNum
     * @param $status
     * @return array
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     */
    private function doBack($orderNum, $status): array {
        $orderInfo = QmGameOrder::query()->where('order_num', $orderNum)->first();
        if ($orderInfo) {
            if ($orderInfo->status != 0) {
                return $this->buildFailed(ErrorCode::NOT_EXISTS, '订单状态异常');
            }
            if ($status != 1 && $status != 2) {
                return $this->buildFailed(ErrorCode::PARAM_INVALID, '订单状态异常');
            }
            if ($status == 1) {
                if ($orderInfo->platform == 2) {
                    $gameInfo = QmGameService::getGameInfo($orderInfo->game_hash);
                    if ($gameInfo['platform'] == 1) {
                        $contentBalance = (new MiMasterService())->getBalance($orderInfo->toArray());
                    } elseif ($gameInfo['platform'] == 2) {
                        $contentBalance = (new TiktokPayService())->getBalance($orderInfo->toArray());
                    }
                    $this->addLog($orderNum, $contentBalance, 'getBalance', $orderInfo->game_hash, $orderInfo->openid);
                    if (isset($contentBalance['balance']) && $contentBalance['balance']) {
                        // 请求平台扣款
                        if ($gameInfo['platform'] == 1) {
                            $content = (new MiMasterService())->doPay($orderInfo->toArray());
                        } elseif ($gameInfo['platform'] == 2) {
                            $content = (new TiktokPayService())->doPay($orderInfo->toArray());
                        }
                        $this->addLog($orderNum, $content, 'doPay', $orderInfo->game_hash, $orderInfo->openid);
                        if ($content['errcode'] != 0) {
                            $orderInfo->status = 2;
                            $orderInfo->error_msg = json_encode($content);
                            $orderInfo->save();

                            return $this->buildFailed(ErrorCode::CURL_ERROR, '支付失败');
                        }
                    } else {
                        $orderInfo->status = 2;
                        $orderInfo->error_msg = '平台账户余额不足，请核实！';
                        $orderInfo->save();

                        return $this->buildFailed(ErrorCode::CURL_ERROR, '支付失败');
                    }
                } else {
                    $client = $this->clientFactory->create(['verify' => false]);
                    $url = "https://darknight.games/api/wx/wx_game/getOrderState";
                    $response = $client->post($url, [
                        'json' => [
                            'orderId' => $orderNum
                        ]
                    ]);
                    $originContent = $response->getBody()->getContents();
                    $content = json_decode($originContent, true);
                    if ($content['code'] != 200 || $content['state'] != 0) {
                        $orderInfo->status = 2;
                        $orderInfo->error_msg = $originContent;
                        $orderInfo->save();

                        return $this->buildFailed(ErrorCode::CURL_ERROR, '支付失败');
                    }
                }
                (new PaySenderInside())->sendReward($orderInfo->toArray());
            }

            $orderInfo->status = $status;
            $orderInfo->save();

            return $this->buildSuccess();
        }

        return $this->buildFailed(ErrorCode::NOT_EXISTS, '订单不存在');
    }

    /**
     * 支付统一下单
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping(path: 'order')]
    public function order(): array {
        $goods_id = $this->request->post('goods_id', '');
        $platform = $this->request->post('platform', 1);
        $game_hash = $this->request->post('game_hash', '');
        $version = $this->request->header('Version', '');
        $user_token = $this->request->header('User-Token', '');
        $platform_from = $this->request->post('platform_from', 1);

        if ($game_hash !=  '1200c5c03478dd50cef65f25b1c2646a') {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '支付系统已关闭');
        }

        //单独关安卓
//        if ($platform == 2) {
//            return $this->buildFailed(ErrorCode::NOT_EXISTS, '支付系统维护中');
//        }
        try {
            $conCode = (new QmGameVersion())->getCode($game_hash, $version);
            $userDataArr = (new GameUserInside())->getUserInfoByToken($user_token, $conCode);
        } catch (\Exception $e) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '下单失败，请重新登录后再次尝试');
        }
        if (empty($userDataArr) || empty($userDataArr['last_role_info'])) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '当前用户不存在');
        }
        if (!is_numeric($platform) || !in_array($platform, [1, 2])) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '下单失败');
        }
        if (!is_numeric($platform_from) || !in_array($platform_from, QmGame::ORDER_PLATFORM)) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '下单失败');
        }

        $shopConf = (new GameConfigInside())->setCode($conCode)->getConfInfoByKey(
            'shop_info', $game_hash, 'id'
        );
        if (isset($shopConf[$goods_id]) && $shopConf[$goods_id]['buy_type'] == 4) {
            if ($shopConf[$goods_id]['shop_type'] == 26) {
                return $this->buildFailed(ErrorCode::NOT_EXISTS, '该商品不存在，无法购买');
                //弹出礼包
//                $redis = (ApplicationContext::getContainer())->get(UserCacheAgent::class);
//                $redisKey = RedisKey::GM_SHOP_TIME_LIMIT . $game_hash . ':' . $userDataArr['last_role_id'] . ':Recharge:' . $goods_id;
//                if (!$redis->exists($redisKey)) {
//                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '弹出礼包不存在，无法购买');
//                }
            }
            if ($shopConf[$goods_id]['shop_type'] == 28) {
                //新手礼包
                $redis = (ApplicationContext::getContainer())->get(PayAgent::class);
                $redisKey = RedisKey::GM_SHOP_RMB . ':' . $userDataArr['game_hash'] . ':Role:' . $userDataArr['last_role_id'];
                $buyTimes = (int)$redis->hGet($redisKey, (string)$goods_id);
                if ($buyTimes >= 1) {
                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '新手礼包已经购买');
                }
            }
            if ($shopConf[$goods_id]['shop_type'] == 29) {
                //至尊月卡
                $endTime = $userDataArr['last_role_info']['extreme_month_vip'];
                if ($endTime >= time()) {
                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '至尊月卡还未过期，无法购买');
                }
            }
            if ($shopConf[$goods_id]['shop_type'] == 35) {
                //新职业战令
                if ($userDataArr['last_role_info']['hero_id'] != 1006) {
                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '职业专属，无法购买');
                }
                $redis = (ApplicationContext::getContainer())->get(PayAgent::class);
                $redisKey = RedisKey::GM_SHOP_RMB . ':' . $userDataArr['game_hash'] . ':Role:' . $userDataArr['last_role_id'];
                $buyTimes = (int)$redis->hGet($redisKey, (string)$goods_id);
                if ($buyTimes >= 1) {
                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '游侠战令已经购买');
                }
            }
            if ($shopConf[$goods_id]['shop_type'] == 40) {
                //十一补给礼包
                $redis = (ApplicationContext::getContainer())->get(PayAgent::class);
                $redisKey = RedisKey::GM_SHOP_RMB . ':' . $userDataArr['game_hash'] . ':Role:' . $userDataArr['last_role_id'];
                $buyTimes = (int)$redis->hGet($redisKey, (string)$goods_id);
                $limit = (int)$shopConf[$goods_id]['buy_limit'];
                if ($limit < 1) {
                    $limit = 1;
                }
                if ($buyTimes >= $limit) {
                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '补给礼包已经购买');
                }
            }
            if ($shopConf[$goods_id]['shop_type'] == 46) {
                //万圣节补给礼包
                $redis = (ApplicationContext::getContainer())->get(PayAgent::class);
                $redisKey = RedisKey::GM_SHOP_RMB . ':' . $userDataArr['game_hash'] . ':Role:' . $userDataArr['last_role_id'];
                $buyTimes = (int)$redis->hGet($redisKey, (string)$goods_id);
                $limit = (int)$shopConf[$goods_id]['buy_limit'];
                if ($limit < 1) {
                    $limit = 1;
                }
                if ($buyTimes >= $limit) {
                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '万圣节礼包无法继续购买');
                }
            }
            if ($shopConf[$goods_id]['shop_type'] == 49) {
                //圣诞补给礼包
                $redis = (ApplicationContext::getContainer())->get(PayAgent::class);
                $redisKey = RedisKey::GM_SHOP_RMB . ':' . $userDataArr['game_hash'] . ':Role:' . $userDataArr['last_role_id'];
                $buyTimes = (int)$redis->hGet($redisKey, (string)$goods_id);
                $limit = (int)$shopConf[$goods_id]['buy_limit'];
                if ($limit < 1) {
                    $limit = 1;
                }
                if ($buyTimes >= $limit) {
                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '圣诞补给礼包无法继续购买');
                }
            }
            if ($shopConf[$goods_id]['shop_type'] == 51) {
                //新年礼包 只能按顺序购买
                $redis = (ApplicationContext::getContainer())->get(PayAgent::class);
                $redisKey = RedisKey::GM_SHOP_RMB . ':' . $userDataArr['game_hash'] . ':Role:' . $userDataArr['last_role_id'];
                $buyTimes = (int)$redis->hGet($redisKey, (string)$goods_id);
                $limit = (int)$shopConf[$goods_id]['buy_limit'];
                if ($limit < 1) {
                    $limit = 1;
                }
                if ($buyTimes >= $limit) {
                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '折扣商店礼包无法继续购买');
                }
                if ($goods_id != 8767) {
                    $new_id = $goods_id - 1;
                    if ((int)$redis->hGet($redisKey, (string)$new_id) < 1) {
                        return $this->buildFailed(ErrorCode::NOT_EXISTS, '必须先购买上一个礼包');
                    }
                }
            }
            if ($shopConf[$goods_id]['shop_type'] == 52) {
                // 只能按顺序购买
                $redis = (ApplicationContext::getContainer())->get(PayAgent::class);
                $redisKey = RedisKey::GM_SHOP_RMB . ':' . $userDataArr['game_hash'] . ':Role:' . $userDataArr['last_role_id'];
                $buyTimes = (int)$redis->hGet($redisKey, (string)$goods_id);
                $limit = (int)$shopConf[$goods_id]['buy_limit'];
                if ($limit < 1) {
                    $limit = 1;
                }
                if ($buyTimes >= $limit) {
                    return $this->buildFailed(ErrorCode::NOT_EXISTS, '该礼包无法继续购买');
                }
            }
            //不允许通过下单购买
            if (in_array($shopConf[$goods_id]['shop_type'], [104, 109])) {
                return $this->buildFailed(ErrorCode::NOT_EXISTS, '当前商品不存在');
            }
            $price = (float)substr($shopConf[$goods_id]['buy_value'], 1, -1);
            $orderNum = date('YmdHis') . md5(uniqid('', true) . $game_hash . 'QM_ONLINE');

            $obj = new QmGameOrder();
            $status = 1;//这里是直接支付成功
            $obj->game_hash = $game_hash;
            $obj->openid = $userDataArr['openid'];
            $obj->uid = $userDataArr['id'];
            $obj->role_id = $userDataArr['last_role_id'];
            $obj->hero_id = $userDataArr['last_role_info']['hero_id'];
            $obj->order_num = $orderNum;
            $obj->goods_id = $goods_id;
            $obj->goods_name = $shopConf[$goods_id]['name_chinese'];
            $obj->prepay_id = '';
            $obj->money = $price;
            $obj->platform = $platform;
            $obj->platform_from = $platform_from;
            $obj->version = $version;
            $obj->number = 1;
            $obj->status = $status;
            $obj->create_date = date('Y-m-d');
            $obj->save();

            //这里是直接支付成功
            $orderInfo = [
                'order_num' => $orderNum,
                'version'   => $version,
                'goods_id'  => $goods_id,
                'game_hash' => $game_hash,
                'openid'    => $userDataArr['openid'],
                'uid'       => $userDataArr['id'],
                'role_id'   => $userDataArr['last_role_id'],
                'hero_id'   => $userDataArr['last_role_info']['hero_id'],
            ];
            if (!empty($orderInfo)) {
                (new PaySenderInside())->sendReward($orderInfo);
            }
            //end

            return $this->buildSuccess([
                'order_num' => $orderNum,
                'price'     => $price,
                'offerId'   => (new MiMasterService())->getOfferId()
            ]);

        }

        return $this->buildFailed(ErrorCode::NOT_EXISTS, '当前商品不存在');
    }

    /**
     * 获取AccessToken
     * @return array
     * @throws GuzzleException
     */
    #[GetMapping(path: 'access_token')]
    public function accessToken(): array {
        $gameHash = $this->request->query('game_hash', '651da2028476d3e669f892fba5014ebe');

        $gameInfo = QmGameService::getGameInfo($gameHash);
        if ($gameInfo['platform'] == 1) {
            $accessToken = (new MiMasterService())->getAccessToken($gameInfo);
        } else if ($gameInfo['platform'] == 2) {
            $accessToken = (new TiktokPayService())->getAccessToken($gameInfo);
        }

        return $this->buildSuccess([
            'access_token' => $accessToken
        ]);
    }


    /**
     * 游戏内用户补单
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping(path: 'backOrder')]
    public function backOrder(): array {
        $version = $this->request->header('Version', '');
        $user_token = $this->request->header('User-Token', '');
        $game_hash = $this->request->post('game_hash', '');

        $gameInfo = QmGameService::getGameInfo($game_hash);
        if (empty($gameInfo)) {
            return $this->buildFailed(ErrorCode::INVALID, '当前游戏不存在');
        }
        try {
            $conCode = (new QmGameVersion())->getCode($game_hash, $version);
            $userDataArr = (new GameUserInside())->getUserInfoByToken($user_token, $conCode);
        } catch (\Exception $e) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '订单');
        }
        if (empty($userDataArr)) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, '当前用户不存在');
        }
        $orderObj = new QmGameOrder();
        $orderObj = $orderObj->where('openid', $userDataArr['openid'])
            ->where('game_hash', $userDataArr['game_hash'])
            ->whereIn('status', [0, 2])
            ->where('created_at', '>', date('Y-m-d H:i:s', time() - 3600 * 3));

        $orderCount = 0;//补单数量
        $orderMoney = 0;//补单金额
        if ($orderObj->count() > 0) {
            $orderList = $orderObj->get();
            foreach ($orderList as $orderInfo) {
                if ($orderInfo['platform'] == 2) {
                    if ($gameInfo['platform'] == 2) {
                        $contentBalance = (new TiktokPayService())->getBalance($orderInfo->toArray());
                    } else if ($gameInfo['platform'] == 1) {
                        $contentBalance = (new MiMasterService())->getBalance($orderInfo->toArray());
                    }
                    if (isset($contentBalance['balance'])
                        && $contentBalance['balance']
                        && (int)$contentBalance['balance'] > 0) {
                        // 请求平台扣款
                        if ($gameInfo['platform'] == 1 && (int)$contentBalance['balance'] == ((int)$orderInfo->money * 10)) {
                            $content = (new MiMasterService())->doPay($orderInfo->toArray());
                        } elseif ($gameInfo['platform'] == 2 && (int)$contentBalance['balance'] == ((int)$orderInfo->money)) {
                            $content = (new TiktokPayService())->doPay($orderInfo->toArray());
                        }
                        if (isset($content) && $content['errcode'] == 0) {
                            (new PaySenderInside())->sendReward($orderInfo->toArray());
                            $orderInfo->status = 1;
                            $orderInfo->save();
                            $orderCount++;
                            $orderMoney += $orderInfo->money;
                            $this->addLogText($orderInfo['order_num'], $content, 'playerBackOrder');
                        }
                    }
                } else {
                    $client = $this->clientFactory->create(['verify' => false]);
                    $url = "https://darknight.games/api/wx/wx_game/getOrderState";
                    $response = $client->post($url, [
                        'json' => [
                            'orderId' => $orderInfo['order_num']
                        ]
                    ]);
                    $originContent = $response->getBody()->getContents();
                    $contentIos = json_decode($originContent, true);
                    if ($contentIos['code'] == 200 && $contentIos['state'] == 0) {
                        (new PaySenderInside())->sendReward($orderInfo->toArray());
                        $orderInfo->status = 1;
                        $orderInfo->save();
                        $orderCount++;
                        $orderMoney += $orderInfo->money;
                        $this->addLogText($orderInfo['order_num'], $contentIos, 'playerBackOrder');
                    }
                }
            }
        }
        return $this->buildSuccess([
            'orderCount' => $orderCount,
            'orderMoney' => $orderMoney
        ]);
    }

    /**
     * 记录订单日志
     * @param $orderNum
     * @param $content
     * @param $type
     * @param $game_hash
     * @param $openid
     * @return void
     */
    private function addLog($orderNum, $content, $type, $game_hash, $openid): void {
        $text = json_encode($content);
        (new PayLogService($type, $orderNum, $text, $game_hash, $openid));
    }

    private function addLogText($orderNum, $content, $type): void {
        $path = '/data/share/order_log/';
        $text = date('Y-m-d H:i:s', time()) . '----' . $orderNum . '----' . $type . '----' . json_encode($content) . PHP_EOL;
        file_put_contents($path . date('Ymd') . '.log', $text, FILE_APPEND);
    }


    #[PostMapping(path: 'userBalance')]
    public function userBalance(): array {
        try {
            $return['balance'] = 0;
            return $this->buildSuccess($return);
            /*
            $game_hash = $this->request->post('game_hash', '');
            $version = $this->request->header('Version', '');
            $user_token = $this->request->header('User-Token', '');
            //判断参数是否为空 否则抛出异常
            if (empty($game_hash) || empty($version) || empty($user_token)) {
                throw new \Exception('缺少参数');
            }

            //判断当前用户是否存在
            $conCode = (new QmGameVersion())->getCode($game_hash, $version);
            $userDataArr = (new GameUserInside())->getUserInfoByToken($user_token, $conCode);
            if (empty($userDataArr)) {
                throw new \Exception('用户不存在');
            }

            //判断是否 微信或者抖音 1微信 2抖音
            $gameInfo = (new QmGameList())->getGameInfo($game_hash);
            if ($gameInfo['platform'] == 2) {
                $contentBalance = (new TiktokPayService())->getBalance(['game_hash' => $game_hash, 'openid' => $userDataArr['openid']]);
                if ($contentBalance['errcode'] == 0 && isset($contentBalance['balance'])) {
                    $return['balance'] = (int)$contentBalance['balance'];
                }
            } else if ($gameInfo['platform'] == 1) {
                $contentBalance = (new MiMasterService())->getBalance(['game_hash' => $game_hash, 'openid' => $userDataArr['openid']]);
                if ($contentBalance['errcode'] == 0 && isset($contentBalance['balance'])) {
                    $return['balance'] = (int)$contentBalance['balance'] / 10;
                }
            }
            return $this->buildSuccess($return);
            */
        } catch (\Exception $e) {
            return $this->buildFailed(ErrorCode::NOT_EXISTS, $e->getMessage());
        }
    }
}